//保存项目到服务器
import queryString from 'query-string';
import xhr from 'xhr';
import storage from '../lib/storage';

/**
 * Save a project JSON to the project server.
 * This should eventually live in scratch-www.
 * @param {number} projectId the ID of the project, null if a new project.
 * @param {object} vmState the JSON project representation.
 * @param {object} params the request params.
 * @property {?string} params.title the title of the project.
 * @return {Promise} A promise that resolves when the network request resolves.
 */
export default function (projectId, vmState, params) {
    const opts = {
        body: vmState,
        // If we set json:true then the body is double-stringified, so don't
        headers: {'Content-Type': 'application/json'},
        withCredentials: true
    };
    const queryParams = {};
    if (params.hasOwnProperty('title')) queryParams.title = params.title;
    let qs = queryString.stringify(queryParams);
    if (qs) qs = `?${qs}`;

    //const creatingProject = projectId === 0;
    if (projectId == 0) {//新建作品
        Object.assign(opts, {
            method: 'post',
            url: `${storage.projectHost}/${qs}`
        });
    } else {//已有作品，更新作品JSON源代码
        Object.assign(opts, {
            method: 'put',
            url: `${storage.projectHost}/${projectId}${qs}`
        });
    }
    return new Promise((resolve, reject) => {
        xhr(opts, (err, response) => {
            if (err) return reject(err);
            if (response.statusCode !== 200) return reject(response.statusCode);

            let body;
            try {
                // Since we didn't set json: true, we have to parse manually
                body = JSON.parse(response.body);
            } catch (e) {
                return reject(e);
            }

            if (projectId != 0) {//如果是新作品，返回的body.id已经就是新作品ID，所以不需要再设置一次
                body.id = projectId;
            }

            resolve(body);
        });
    });
}
